package com.yln.watcher;

import com.yln.watcher.client.ZkClient;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;

import java.util.List;

@Slf4j
@RequiredArgsConstructor
public class AssignedTaskWatcher implements Watcher {

    private final ZkClient zkClient;

    @Override
    public void process(WatchedEvent event) {
        Event.EventType eventType = event.getType();
        log.info("assigned task watcher triggered. eventType: {}", eventType);
        switch (eventType) {
            case NodeChildrenChanged:
                List<String> addedTasks = zkClient.findAllAssignedTasksByClient();
                List<String> cacheAssignedTasks = zkClient.getCacheAssignedTasks();
                addedTasks.removeAll(cacheAssignedTasks);
                log.info("added new assigned tasks: {}", addedTasks);
                addedTasks.forEach(taskNode -> {
                    zkClient.doJob(taskNode);
                });
                break;
            default:
                break;
        }
    }
}
